package com.app.backend.common.serviceImpl;

import com.app.backend.common.service.RedisHashService;
import org.springframework.data.redis.core.HashOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;
import java.util.Set;
import java.util.concurrent.TimeUnit;

/**
 * @program: RedisHashServiceImpl
 * @description: redis hash操作实现类
 * @author: Zhun.Xiao
 * @create: 2018-10-29 16:18
 **/
@Service
public class RedisHashServiceImpl<T> implements RedisHashService<T> {


    @Resource
    protected RedisTemplate<String, T> redisTemplate;
    @Resource
    protected HashOperations<String, String, T> hashOperations;


    @Override
    public void put(String redisKey, String key, T doamin, long expire) {
        hashOperations.put(redisKey, key, doamin);
        if (expire != -1) {
            redisTemplate.expire(redisKey, expire, TimeUnit.SECONDS);
        }
    }

    @Override
    public void remove(String redisKey, String key) {
        hashOperations.delete(redisKey, key);
    }

    @Override
    public T get(String redisKey, String key) {
        return hashOperations.get(redisKey, key);
    }

    @Override
    public List<T> getAll(String redisKey) {
        return hashOperations.values(redisKey);
    }

    @Override
    public Set<String> getKeys(String redisKey) {
        return hashOperations.keys(redisKey);
    }

    @Override
    public boolean isKeyExists(String redisKey, String key) {
        return hashOperations.hasKey(redisKey, key);
    }

    @Override
    public long count(String redisKey) {
        return hashOperations.size(redisKey);
    }

    @Override
    public void empty(String redisKey) {
        Set<String> set = hashOperations.keys(redisKey);
        set.stream().forEach(key -> hashOperations.delete(redisKey, key));
    }
}
